package com.monolithiot.sso.controller.front;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.entity.Authorization;
import com.monolithiot.sso.common.util.ReturnUrlUtil;
import com.monolithiot.sso.common.util.SessionAttributeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpSession;

/**
 * 2018/12/13 Create by 郭文梁
 * RedirectController
 * 重定向控制器，负责鉴权/授权完成后重定向到客户系统的地址
 *
 * @author 郭文梁
 * @date 2018/12/13
 */
@Controller
@RequestMapping("/front/redirect")
public class RedirectController {
    /**
     * 携带令牌返回到回调地址
     *
     * @param authorization 授权对象
     * @param session       会话
     * @return redirect url
     */
    @GetMapping("/return")
    public String returnUrl(@SessionAttribute(Constants.Key.SESSION_AUTHORIZATION) Authorization authorization,
                            HttpSession session) {
        String returnUrl = SessionAttributeUtil.fromSessionOrDefault(session, String.class,
                Constants.Key.SESSION_AUTHORIZATION_RETURN_URL,
                Constants.View.DEFAULT_RETURN_URL);

        String targetUrl = ReturnUrlUtil.appendToken(returnUrl, authorization.getToken());
        return Constants.View.redirect(targetUrl);
    }
}
